
import React, { useState, useEffect, useCallback } from 'react';
import { ChartDataPoint, TrainingParameters, TaskType, ModelInfo } from '../types';
import ChartComponent from './ChartComponent';
import { Button, Panel, FileUploader, ModelSelector } from './shared';
import { PlayIcon, StopCircleIcon, TrashIcon } from './icons';
import { simulationService } from '../services/simulationService';
import { ollamaService } from '../services/geminiService';
import { getModels, startJob, getJobStatus } from '../services/backendApi';


const generateIdleData = (points = 50) => {
    const data: ChartDataPoint[] = [];
    for (let i = 0; i < points; i++) {
        data.push({ step: i, value: Math.random() });
    }
    return data;
};


interface ValidateModelViewProps {
  isGpuBusy: boolean;
  setIsGpuBusy: (isBusy: boolean) => void;
  setStatusMessage: (message: string) => void;
}

const ValidateModelView = ({ isGpuBusy, setIsGpuBusy, setStatusMessage }: ValidateModelViewProps) => {
  const [isRunning, setIsRunning] = useState(false);
  const [lossData, setLossData] = useState<ChartDataPoint[]>(() => generateIdleData());
  const [accuracyData, setAccuracyData] = useState<ChartDataPoint[]>(() => generateIdleData());
  const [guidance, setGuidance] = useState<string>('系统待机中... 等待验证任务指令。');


  const [fileName, setFileName] = useState<string | null>(null);
  const [selectedModel, setSelectedModel] = useState<string | null>(null);
  const [models, setModels] = useState<ModelInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [jobId, setJobId] = useState<string | null>(null);



  const clearState = useCallback(() => {
    setIsRunning(false);
    setIsGpuBusy(false);
    setLossData(generateIdleData());
    setAccuracyData(generateIdleData());
    setGuidance('系统待机中... 等待验证任务指令。');
    setFileName(null);
    setSelectedModel(null);
    setStatusMessage('状态: 空闲');
  }, [setIsGpuBusy, setStatusMessage]);


  // 初次渲染自动加载
  useEffect(() => {
    loadModels();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const loadModels = async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await getModels();
      setModels(data);
    } catch (e) {
      setError('获取模型列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleStop = () => {
    simulationService.stop();
    setIsRunning(false);
    setIsGpuBusy(false);
    setStatusMessage('验证任务已由用户手动中止。');
  };

  const handleFileUpload = (file: File) => {
    setFileName(file.name);
    setStatusMessage(`文件已上传: ${file.name}`);
  };

  const handleStart = async () => {
    if (!fileName || !selectedModel) {
      setStatusMessage('错误: 请先选择模型并上传验证JSON文件');
      return;
    }

    try {
      setIsRunning(true);
      setIsGpuBusy(true);
      setLossData([]);
      setAccuracyData([]);
      setGuidance('正在初始化验证环境...');
      setStatusMessage('正在启动验证任务...');

      // 调用后端启动验证任务
      const response = await startJob({
        taskType: 'Validation',
        dataFile: fileName,
        modelId: selectedModel,
        params: {
          batchSize: 32,
          numWorkers: 4
        }
      });

      if (response.success) {
        const currentJobId = response.jobId;
        setJobId(currentJobId);
        setStatusMessage(`验证任务已启动，任务ID: ${currentJobId}`);
        
        // 开始轮询任务状态
        pollJobStatus(currentJobId);
      } else {
        throw new Error('启动任务失败');
      }
    } catch (error) {
      console.error('启动验证任务失败:', error);
      setStatusMessage(`错误: ${error instanceof Error ? error.message : '启动验证任务失败'}`);
      setIsRunning(false);
      setIsGpuBusy(false);
    }
  };

  const pollJobStatus = async (currentJobId: string) => {
    const pollInterval = setInterval(async () => {
      try {
        const status = await getJobStatus(currentJobId);
        
        // 更新进度数据
        if (status.progress) {
          const { epoch, step, totalSteps, loss, accuracy } = status.progress;
          if (loss !== undefined && accuracy !== undefined) {
            setLossData(prev => [...prev, { step: (epoch - 1) * totalSteps + step, value: loss }]);
            setAccuracyData(prev => [...prev, { step: (epoch - 1) * totalSteps + step, value: accuracy }]);
          }
          setStatusMessage(`验证中... [轮次 ${epoch}] [步骤 ${step}/${totalSteps}]`);
        }

        // 检查任务完成状态
        if (status.status === 'completed') {
          clearInterval(pollInterval);
          setStatusMessage('验证完成！正在生成AI分析报告...');
          
          // 获取最终的验证结果并请求AI分析
          const finalLoss = lossData[lossData.length - 1]?.value || 0;
          const finalAccuracy = accuracyData[accuracyData.length - 1]?.value || 0;
          
          try {
            const analysis = await ollamaService.analyzeValidationResults(finalLoss, finalAccuracy);
            setGuidance(analysis);
          } catch (error) {
            setGuidance('验证完成，但AI分析生成失败。');
          }
          
          setStatusMessage('验证任务完成！');
          setIsRunning(false);
          setIsGpuBusy(false);
          setJobId(null);
        } else if (status.status === 'failed') {
          clearInterval(pollInterval);
          setStatusMessage(`验证任务失败: ${status.message || '未知错误'}`);
          setIsRunning(false);
          setIsGpuBusy(false);
          setJobId(null);
        } else if (status.status === 'stopped') {
          clearInterval(pollInterval);
          setStatusMessage('验证任务已停止');
          setIsRunning(false);
          setIsGpuBusy(false);
          setJobId(null);
        }
      } catch (error) {
        console.error('获取任务状态失败:', error);
        clearInterval(pollInterval);
        setStatusMessage('获取任务状态失败，验证可能仍在进行中');
        setIsRunning(false);
        setIsGpuBusy(false);
        setJobId(null);
      }
    }, 2000); // 每2秒轮询一次

    // 保存轮询间隔ID以便在组件卸载时清理
    return () => clearInterval(pollInterval);
  };



  return (
    <div className="p-4 flex flex-col gap-4 h-full hacker-scrollbar overflow-y-auto">
      <Panel title="任务控制">
        <div className="flex flex-wrap gap-4 items-end">
            <ModelSelector
              selectedModel={selectedModel}
              onSelectModel={setSelectedModel}
              disabled={isRunning || isGpuBusy}
            />
            <div className="flex flex-col gap-2">
                <label className="text-sm text-green-300">上传数据</label>
                <FileUploader onFileUpload={handleFileUpload} buttonText="上传验证JSON" disabled={isRunning || isGpuBusy} />
            </div>
            {fileName && <span className="text-cyan-300 text-sm self-center pt-8">已加载: {fileName}</span>}
            <div className="flex-grow" />
            <Button onClick={handleStart} disabled={isRunning || isGpuBusy || !fileName || !selectedModel} icon={<PlayIcon className="w-4 h-4" />}>开始验证</Button>
            <Button onClick={handleStop} disabled={!isRunning} icon={<StopCircleIcon className="w-4 h-4" />}>停止</Button>
            <Button onClick={clearState} disabled={isRunning} icon={<TrashIcon className="w-4 h-4" />}>清空</Button>
        </div>
      </Panel>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <ChartComponent data={lossData} title="验证损失 (Loss)" lineColor="#ff4d4d" dataKey="value" />
        <ChartComponent data={accuracyData} title="验证准确率 (Accuracy)" lineColor="#00ffff" dataKey="value" />
      </div>

      <Panel title="智能分析与指导" className="flex-grow">
        <div className="h-full whitespace-pre-wrap text-sm text-cyan-200 hacker-scrollbar overflow-y-auto" style={{maxHeight: '250px'}}>
            {guidance}
        </div>
      </Panel>
    </div>
  );
};

export default ValidateModelView;